# 用户服务层，处理与用户相关的业务逻辑
from models import User
from extensions import db


def get_all_users():
    """获取所有用户
    
    Returns:
        list: 用户列表
    """
    return User.query.all()


def get_user_by_id(user_id):
    """根据ID获取用户
    
    Args:
        user_id (int): 用户ID
    
    Returns:
        User: 用户对象或None
    """
    return User.query.get(user_id)


def create_user(username, email):
    """创建新用户
    
    Args:
        username (str): 用户名
        email (str): 电子邮箱
    
    Returns:
        User: 创建的用户对象
    """
    new_user = User(username=username, email=email)
    db.session.add(new_user)
    db.session.commit()
    return new_user


def update_user(user_id, username=None, email=None):
    """更新用户信息
    
    Args:
        user_id (int): 用户ID
        username (str, optional): 新用户名
        email (str, optional): 新电子邮箱
    
    Returns:
        User: 更新后的用户对象或None
    """
    user = get_user_by_id(user_id)
    if not user:
        return None
    
    if username:
        user.username = username
    if email:
        user.email = email
    
    db.session.commit()
    return user


def delete_user(user_id):
    """删除用户
    
    Args:
        user_id (int): 用户ID
    
    Returns:
        bool: 是否删除成功
    """
    user = get_user_by_id(user_id)
    if not user:
        return False
    
    db.session.delete(user)
    db.session.commit()
    return True